import React, { useState, useEffect } from 'react';
import {
  Card,
  Button,
  Space,
  Typography,
  Divider,
  Tag,
  Alert,
  List,
  Row,
  Col,
  Statistic,
  Progress
} from 'antd';
import {
  ReloadOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SettingOutlined,
  BranchesOutlined,
  UserOutlined
} from '@ant-design/icons';
import { useAuth } from '../contexts/AuthContext';
import { usePermissionSync } from '../hooks/usePermissionSync';
import { menuService } from '../services/menuService';
import { showNotification } from '../utils/notification';
import api from '../services/api';

const { Title, Text, Paragraph } = Typography;

const RoutePermissionTest: React.FC = () => {
  const { state, hasPermission } = useAuth();
  const [menuItems, setMenuItems] = useState<any[]>([]);
  const [routeStats, setRouteStats] = useState<any>(null);
  const [testResults, setTestResults] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);

  // 使用权限同步Hook
  const { currentPermissions, checkPermissions } = usePermissionSync({
    onPermissionChange: (newPermissions) => {
      showNotification('info', '权限已更新', `当前权限数量: ${newPermissions.length}`);
      runTests();
    },
    debug: true
  });

  /**
   * 运行测试
   */
  const runTests = async () => {
    setLoading(true);
    const results = [];

    try {
      // 测试1: 菜单加载
      try {
        const menu = await menuService.getUserMenu(true);
        const filteredMenu = menuService.filterMenuByPermissions(menu, hasPermission);
        setMenuItems(filteredMenu);
        results.push({
          name: '菜单加载测试',
          status: 'success',
          message: `成功加载 ${filteredMenu.length} 个菜单项`,
          details: filteredMenu.map(item => item.label).join(', ')
        });
      } catch (error: any) {
        results.push({
          name: '菜单加载测试',
          status: 'error',
          message: '菜单加载失败',
          details: error.message
        });
      }

      // 测试2: 路由统计
      try {
        const response = await api.get('/v1/routes/statistics');
        setRouteStats(response.data.data);
        results.push({
          name: '路由统计测试',
          status: 'success',
          message: `统计数据获取成功`,
          details: `总路由: ${response.data.data.total_routes}, 活跃: ${response.data.data.active_routes}`
        });
      } catch (error: any) {
        results.push({
          name: '路由统计测试',
          status: 'error',
          message: '统计数据获取失败',
          details: error.message
        });
      }

      // 测试3: 权限检查
      const testPermissions = ['user.view', 'role.view', 'route.view', 'lineage.view'];
      const permissionResults = testPermissions.map(permission => ({
        permission,
        hasAccess: hasPermission(permission)
      }));
      
      results.push({
        name: '权限检查测试',
        status: 'success',
        message: `检查了 ${testPermissions.length} 个权限`,
        details: permissionResults.map(r => `${r.permission}: ${r.hasAccess ? '✓' : '✗'}`).join(', ')
      });

      // 测试4: 自动配置权限（仅测试API可用性）
      try {
        // 这里只测试API是否可访问，不实际执行
        await api.get('/v1/routes');
        results.push({
          name: '路由API测试',
          status: 'success',
          message: '路由API访问正常',
          details: '可以正常访问路由管理API'
        });
      } catch (error: any) {
        results.push({
          name: '路由API测试',
          status: 'error',
          message: '路由API访问失败',
          details: error.message
        });
      }

    } catch (error) {
      console.error('测试执行失败:', error);
    }

    setTestResults(results);
    setLoading(false);
  };

  useEffect(() => {
    runTests();
  }, []);

  const successCount = testResults.filter(r => r.status === 'success').length;
  const totalCount = testResults.length;
  const successRate = totalCount > 0 ? Math.round((successCount / totalCount) * 100) : 0;

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <Title level={3}>
          <SettingOutlined style={{ marginRight: 8 }} />
          路由权限系统测试
        </Title>
        <Paragraph type="secondary">
          测试动态路由菜单和权限管理系统的各项功能是否正常工作
        </Paragraph>

        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col xs={24} sm={8}>
            <Card size="small">
              <Statistic
                title="当前权限数量"
                value={currentPermissions.length}
                prefix={<UserOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={8}>
            <Card size="small">
              <Statistic
                title="菜单项数量"
                value={menuItems.length}
                prefix={<BranchesOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={8}>
            <Card size="small">
              <Statistic
                title="测试通过率"
                value={successRate}
                suffix="%"
                prefix={<CheckCircleOutlined />}
                valueStyle={{ color: successRate === 100 ? '#52c41a' : '#fa8c16' }}
              />
            </Card>
          </Col>
        </Row>

        <div style={{ marginBottom: 16 }}>
          <Progress 
            percent={successRate} 
            status={successRate === 100 ? 'success' : 'active'}
            strokeColor={successRate === 100 ? '#52c41a' : '#1890ff'}
          />
        </div>

        <Space style={{ marginBottom: 16 }}>
          <Button 
            type="primary" 
            icon={<ReloadOutlined />} 
            onClick={runTests}
            loading={loading}
          >
            重新测试
          </Button>
          <Button 
            icon={<CheckCircleOutlined />} 
            onClick={checkPermissions}
          >
            检查权限变更
          </Button>
        </Space>

        <Divider />

        <Title level={4}>测试结果</Title>
        <List
          dataSource={testResults}
          renderItem={(item) => (
            <List.Item>
              <List.Item.Meta
                avatar={
                  item.status === 'success' ? 
                    <CheckCircleOutlined style={{ color: '#52c41a', fontSize: 16 }} /> :
                    <CloseCircleOutlined style={{ color: '#ff4d4f', fontSize: 16 }} />
                }
                title={
                  <Space>
                    <Text strong>{item.name}</Text>
                    <Tag color={item.status === 'success' ? 'success' : 'error'}>
                      {item.status === 'success' ? '通过' : '失败'}
                    </Tag>
                  </Space>
                }
                description={
                  <div>
                    <div>{item.message}</div>
                    {item.details && (
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        详情: {item.details}
                      </Text>
                    )}
                  </div>
                }
              />
            </List.Item>
          )}
        />

        {routeStats && (
          <>
            <Divider />
            <Title level={4}>系统统计</Title>
            <Alert
              message="路由统计信息"
              description={
                <div>
                  <p>总路由数: {routeStats.total_routes}</p>
                  <p>活跃路由: {routeStats.active_routes}</p>
                  <p>菜单路由: {routeStats.menu_routes}</p>
                  <p>权限关联: {routeStats.permission_associations}</p>
                </div>
              }
              type="info"
              showIcon
            />
          </>
        )}

        <Divider />
        <Title level={4}>当前权限列表</Title>
        <div>
          {currentPermissions.length > 0 ? (
            <Space wrap>
              {currentPermissions.map(permission => (
                <Tag key={permission} color="blue">{permission}</Tag>
              ))}
            </Space>
          ) : (
            <Text type="secondary">暂无权限信息</Text>
          )}
        </div>
      </Card>
    </div>
  );
};

export default RoutePermissionTest;
